package com.stylefeng.guns.modular.train.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.common.constant.Const;
import com.stylefeng.guns.common.persistence.model.ContestPoints;
import com.stylefeng.guns.common.persistence.model.Dept;
import com.stylefeng.guns.common.persistence.model.Dict;
import com.stylefeng.guns.common.persistence.model.Employee;
import com.stylefeng.guns.config.excel.ExcelExportStylerImpl;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.base.tips.ErrorTip;
import com.stylefeng.guns.core.base.tips.SuccessTip;
import com.stylefeng.guns.core.base.tips.Tip;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.modular.system.service.IDeptService;
import com.stylefeng.guns.modular.system.service.IDictService;
import com.stylefeng.guns.modular.train.service.IEmployeeService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

/**
 * employee控制器
 *
 * @author fengshuonan
 * @Date 2017-12-21 22:37:38
 */
@Controller
@RequestMapping("/employee")
public class EmployeeController extends BaseController {

    private String PREFIX = "/train/employee/";

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IDictService dictService;

    @Autowired
    private IDeptService deptService;

    private static String EMPNAME_STATIC = null;

    /**
     * 跳转到employee首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "employee.html";
    }

    /**
     * 跳转到选择employee页面
     */
    @RequestMapping(value = "/select_list")
    public String selectList(String empName) {
        EMPNAME_STATIC = empName;
        return PREFIX + "emp_list_select.html";
    }

    /**
     * 跳转到选择employee页面
     */
    @RequestMapping(value = "/select_list_checkbox")
    public String selectListCheckbox() {
        return PREFIX + "emp_list_checkbox.html";
    }


    /**
     * 跳转到添加employee
     */
    @RequestMapping("/employee_add")
    public String employeeAdd(Model model) {
        List<Dict> byPName = dictService.getByPName(Const.POST_TYPE);
        List<Dept> firstLevelDept = deptService.getFirstLevelDept();
        List<Dict> laborTypes = dictService.getChildByCode(Const.LABOR_TYPE);
        model.addAttribute("depts",firstLevelDept);
        model.addAttribute("groups",byPName);
        model.addAttribute("laborTypes",laborTypes);
        return PREFIX + "employee_add.html";
    }

    /**
     * 跳转到选择employee g_search页面
     */
    @RequestMapping(value = "/g_search")
    public String gSearch(Model model) {
        List<Dept> depts = deptService.getFirstLevelDept();
        List<Dict> posts = dictService.getByPName(Const.POST_TYPE);
        model.addAttribute("depts",depts);
        model.addAttribute("posts",posts);
        return PREFIX + "g_search.html";
    }

    /**
     * 跳转到修改employee
     */
    @RequestMapping("/employee_update/{employeeId}")
    public String employeeUpdate(@PathVariable String employeeId, Model model) {
        Employee employee = employeeService.selectById(employeeId);
        List<Dict> byPName = dictService.getByPName(Const.POST_TYPE);
        List<Dict> laborTypes = dictService.getChildByCode(Const.LABOR_TYPE);
        List<Dept> depts = deptService.getFirstLevelDept();
        List<Dept> places = new ArrayList<>();
        List<Dept> teams = new ArrayList<>();
        if(!StringUtils.isEmpty(employee.getDepartment())){
            places = deptService.getTwoLevelDeptByName(employee.getDepartment());
        }
        if(!StringUtils.isEmpty(employee.getPlace())){
            Map<String,String> map = new HashMap<>();
            for (Dept place : places) {
                map.put(place.getFullname(),place.getId());
            }

            teams = deptService.getThreeLevelDept(map.get(employee.getPlace()));
        }
        model.addAttribute("depts",depts);
        model.addAttribute("places",places);
        model.addAttribute("teams",teams);
        model.addAttribute("laborTypes",laborTypes);

        model.addAttribute("item",employee);
        LogObjectHolder.me().set(employee);
        model.addAttribute("groups",byPName);
        return PREFIX + "employee_edit.html";
    }

    /**
     * 获取employee列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(Employee employee) {
        if(!StringUtils.isEmpty(EMPNAME_STATIC)){
           employee.setEmpName(EMPNAME_STATIC);
            EMPNAME_STATIC = null;
        }
        EntityWrapper<Employee> wrapper = new EntityWrapper<>();
        wrapper.setEntity(employee);
        List<Employee> employees = employeeService.selectList(wrapper);

        convertToString(employees);

        return employees;
    }


    /**
     * 新增employee
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(Employee employee) {
        Employee employee1 = employeeService.selectByCode(employee.getEmpCode());
        if(employee1 != null){
            return new ErrorTip(500,"保存失败！ 已经存在"+ employee1.getEmpCode() + "的员工！");
        }
        employee.setCreateType(Const.IMPORT_TYPE_SYS);
        employee.setCreateDate(new Date());
        employeeService.insert(employee);
        return super.SUCCESS_TIP;
    }

    /**
     * 删除employee
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam String employeeId) {
        if(employeeId.contains(",")){
            List<String> ids = Arrays.asList(employeeId.split(","));
            employeeService.deleteBatchIds(ids);
        }else{
            employeeService.deleteById(employeeId);
        }
        return SUCCESS_TIP;
    }

    /**
     * 修改employee
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(Employee employee) {
        System.out.println("修改-----"+employee.toString());
       employeeService.updateById(employee);
        return super.SUCCESS_TIP;
    }

    /**
     * employee详情
     */
    @RequestMapping(value = "/detail/{employeeId}")
    @ResponseBody
    public Object detail(@PathVariable("employeeId") String employeeId) {
        return employeeService.selectById(employeeId);
    }

    @RequestMapping(value = "/detailByCode/{empCode}")
    @ResponseBody
    public Object detailByCode(@PathVariable("empCode") String empCode) {
        return employeeService.selectByCode(empCode);
    }

    /**
     * 跳转到导入employee
     */
    @RequestMapping("/employee_import")
    public String employeeImport() {
        return PREFIX + "employee_import.html";
    }

    /**
     * 导入employee
     */
    @RequestMapping(value = "/import")
    @ResponseBody
    public Object imports(MultipartHttpServletRequest mutReq) throws Exception {

        ImportParams params = new ImportParams();

        params.setStartRows(0);
        params.setTitleRows(0);
        int count = 2;
        try {
            List<Employee> employees = ExcelImportUtil.importExcel(mutReq.getFile("file").getInputStream(), Employee.class, params);
            Date now = new Date();
//            Map<String, List> orgMap = deptService.getOrgMap();
            Set<String> fullnames = new HashSet<>();
            for (Dept dept : deptService.selectList(null)) {
                fullnames.add(dept.getFullname());
            }

            Map<String, String> postTypes = dictService.getMapNameNumByPcode(Const.POST_TYPE_CODE);
            List<Employee> employees1 = employeeService.selectList(null);
            Set<String> empCodes = new HashSet<>();
            employees1.forEach(e->empCodes.add(e.getEmpCode()));

            for (Employee employee : employees) {
                employee.setCreateType(Const.IMPORT_TYPE_XML);
                employee.setCreateDate(now);


                if(empCodes.contains(employee.getEmpCode())){
                    throw new Exception("已经存在"+ employee.getEmpCode() + "的员工,请检查数据！");
                }

                String postNamNum = postTypes.get(employee.getPostType().trim());
                if(StringUtils.isEmpty(postTypes)){
                    throw new Exception("数据中的岗位类别不存在，请先维护岗位类别！");
                }
                employee.setPostType(postNamNum);

                if(!StringUtils.isEmpty(employee.getDeptName())){

                    if(fullnames.contains(employee.getDeptName())){
                        employee.setDepartment(employee.getDeptName());

                        if(!StringUtils.isEmpty(employee.getTeamName())){
                            if(fullnames.contains(employee.getTeamName())){
                                employee.setTeam(employee.getTeamName());
                                if(StringUtils.isEmpty(employee.getPlaceName())){
                                    employee.setPlaceName("无");
                                }

                                if(!fullnames.contains(employee.getPlaceName())){
                                    throw new Exception("处室 "+employee.getPlaceName()+" 不存在，请先维护组织机构！");
                                }else{
                                    employee.setPlace(employee.getPlaceName());
                                }
                            }else{
                                throw new Exception("班组 "+employee.getTeamName()+" 不存在，请先维护组织机构！");
                            }

                        }
                    }else{
                        throw new Exception("部门 "+employee.getDeptName()+" 不存在，请先维护组织机构！");
                    }

                }
                count++;
            }
            employeeService.insertBatch(employees);
        } catch (Exception e) {
            e.getStackTrace();
            return new ErrorTip(400,"第"+ count+"条 " +e.getMessage());
        }
        SuccessTip successTip = super.SUCCESS_TIP;
        successTip.setMessage(String.format("成功插入%d", count-2)  + "条数据");
        return successTip;
    }

    /**
     * 导出
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response) {
        try {
            List<Employee> employees= employeeService.selectList(null);
            convertToString(employees);
            ExportParams exportParams=new ExportParams("员工基本信息统计表", "员工基本信息统计表");
            exportParams.setStyle(ExcelExportStylerImpl.class);
            exportParams.setTitleHeight((short)14);
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, Employee.class, employees);
            OutputStream outputStream=response.getOutputStream();
            String fileName="员工基本信息统计表.xls";
            response.addHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes(),"ISO-8859-1"));
            workbook.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 转换一些代码为文字
     * @param employees
     */
    private void convertToString(List<Employee> employees){
        List<Dict> byPName = dictService.getByPName(Const.POST_TYPE);
        Map<String,String> postTypeMap = new HashMap<>();

        for (Dict dict : byPName) {
            postTypeMap.put(dict.getNum().toString(), dict.getName().toString());
        }

        for (Employee employee : employees) {
            String name = postTypeMap.get(employee.getPostType());
            employee.setPostType(name);
        }
    }
}
